package com.example.demo.tools;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author xin
 */
@ServerEndpoint("/websocket")
@Component
public class CustomWebSocket {
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<CustomWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;

    private static final Logger logger = LoggerFactory.getLogger(CustomWebSocket.class);

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        logger.info("新连接接入。当前在线人数：" + getOnlineCount());
        try {
            sendMessage("假装有内容");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        logger.info("有连接关闭，当前在线人数：" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("客户端发送的信息：" + message);
        sendAll(session.getId() + ":\n" + message);
    }

    public static void sendInfo(String message) {
        sendAll(message);
    }

    private static void sendAll(String message) {
        Arrays.asList(webSocketSet.toArray()).forEach(item -> {
            CustomWebSocket customWebSocket = (CustomWebSocket) item;
            try {
                customWebSocket.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("有异常啦");
        error.printStackTrace();
    }

    private void subOnlineCount() {
        CustomWebSocket.onlineCount--;
    }

    private void addOnlineCount() {
        CustomWebSocket.onlineCount++;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public void sendMessage(String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }
}
